<!DOCTYPE html>
<html>
<head>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <link rel="stylesheet" href="component/layui/css/layui.css" />
    <script src="js/jQuery.js"></script>
    <SCRIPT src="js/common.js"></SCRIPT>
    <script src="../../../component/layui/layui.js"></script>
<body style="padding-top: 5px">
<form class="layui-form layui-form-pane" action="">
    
            <div class="layui-form-item">
               <label class="layui-form-label">用户范围</label>
                <div class="layui-input-block">
                    <select id="selectRange" lay-verify="required">
                     <option value=''>请选择</option>
                     <option value='0'>默认</option>
                </select>
                </div>
            </div>
            <div class="layui-form-item" pane lay-filter="check">
                <label class="layui-form-label">权限类型</label>
                <div class="layui-input-block">
                    <input  type="checkbox" name="type" value="0" title="上传" lay-skin="primary" >
                    <input  type="checkbox" name="type" value="1" title="下载（查看）" lay-skin="primary">
                    <input  type="checkbox" name="type" value="2" title="删除" lay-skin="primary">
                    <input  type="checkbox" name="type" value="3" title="创建文件夹" lay-skin="primary">
                    <input  type="checkbox" name="type" value="4" title="分享" lay-skin="primary">
                    <input  type="checkbox" name="type" value="5" title="重命名" lay-skin="primary">
                </div>
            </div>
            <div class="layui-form-item">
                <div style="text-align: right" class="button-container">
                <button class="layui-btn layui-btn-sm" lay-submit lay-filter="settingForm">
                    <i class="layui-icon layui-icon-ok"></i>
                                  提交
                </button>
                <button type="reset" class="layui-btn layui-btn-primary layui-btn-sm" >
                <i class="layui-icon layui-icon-refresh"></i>
                                 重置
                </button>
                </div>
            </div>
</form>
</body>
<script>
    //勾选的需要配置的文件
    var checkStatus = parent.PartitionId
    //console.log(checkStatus);
    //动态加载部门范围选择
    var departmentresult={};
    $(function () {
        var department={}
        $.ajax({
            url: sessionStorage.getItem("rootPath") + "/departments/selectDepartmentList",
            method: "post",
            dataType: "json",
            contentType: 'application/json;charset=utf-8',
            data: JSON.stringify(department),
            success: function (res) {
                departmentresult=res;
                //$("#selectRange").prepend("<option value='0'>请选择</option>");//添加第一个option值
                //console.log(departmentresult.data.length);
                for (var i=0; i<departmentresult.data.length;i++){
                    $('#selectRange').append(new Option(departmentresult.data[i].departmentName,departmentresult.data[i].id));
                }
                layui.form.render("select");

            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                console.log("失败" + XMLHttpRequest.status + ":" + textStatus + ":" + errorThrown);
            }
        })
    });
//提交
layui.use('form', function(){
  var form = layui.form;
  var departmentId;
  var fileId;
  form.on('select()', function(data){
	  departmentId = data.value;
	  
	  if(checkStatus.data.length>0){
		  fileId = checkStatus.data[0].fileId;              //默认获取第一个文件的权限
	  }else{
		  layui.use('layer', function() { //独立版的layer无需执行这一句
	            var $ = layui.jquery, layer = layui.layer; //独立版的layer无需执行这一句
	            layer.alert('请至少选择一个文件');
	        })
	  }
	  
	  if(departmentId == 0){
		  getPermission(null,fileId)
	  }else{
		  getPermission(departmentId,fileId)
	  }
	}); 
  //监听提交
  form.on('submit(settingForm)', function(data){
	 var inputs = document.getElementsByName("type");
	 if(checkStatus.data.length>0){
		 //console.log("长度"+checkStatus.data.length);
		 //遍历下载
	        for(var i=0;i<checkStatus.data.length;i++){
		        
	        	var obsFile={};
	        	var temp;             //单个权限值
	        	var values = "";      //总的二进制权限
	        	var num;              //十进制权限值
	        	
	        	fileId = checkStatus.data[i].fileId;
	        	//console.log("文件id "+fileId);
		        
		        for(var j = 0; j < inputs.length;j++){
		            if (inputs[j].checked){
		          	  //console.log("权限值"+inputs[j].value);
		          	  temp  = "1";
		            }else{
		              temp = "0";
		            }
		            values = temp + values;
		        }
		        
		        num = parseInt(values,2)  //换算成10进制
		        
		        console.log("文件id "+fileId);
		        console.log("部门id "+departmentId);
		        console.log("2进制权限值 "+values);
		        console.log("10进制权限值 "+num);
		        
		        obsFile.departmentId = departmentId;
		        obsFile.fileId = fileId;
		        obsFile.permission = num;
		        
		        console.log("参数 "+obsFile);
		        $.ajax({
	                url: sessionStorage.getItem("rootPath") + "/files/permission",
	                data:obsFile,
	                type:'post',
	                success:function(res){
	                    layer.msg("权限设置成功！",{icon:1,time:1000},function () {
	                    	var index = parent.layer.getFrameIndex(window.name);
                            parent.layer.close(index);
	                    });
	                },
	                error: function (XMLHttpRequest, textStatus, errorThrown) {
	                    layer.msg("权限设置失败！" ,{icon:2,time:1000});
	                    console.log("失败" + XMLHttpRequest.status + ":" + textStatus + ":" + errorThrown);
	                }
	            })
	        }
	   }else{
		   layui.use('layer', function() { //独立版的layer无需执行这一句
	            var $ = layui.jquery, layer = layui.layer; //独立版的layer无需执行这一句
	            layer.alert('请至少选择一个文件');
	        })
	   }
      return false
  });
});

//请求文件的权限
function getPermission(departmentId,fileId){
	var permission;
	var obsFile={};
	if(departmentId != null){
		obsFile.departmentId = departmentId;
	}
     $.ajax({
	          url: sessionStorage.getItem("rootPath") + "/files/permission/"+fileId,
	          data:obsFile,
	          type:'GET',
	          success:function(res){
	             permission = binary(res.data,6);
                 console.log(permission);
	          },
	          error: function (XMLHttpRequest, textStatus, errorThrown) {
	             console.log("失败" + XMLHttpRequest.status + ":" + textStatus + ":" + errorThrown);
	          }
	  })
     return permission;
}

//十进制数换成6位二进制数
function binary(num, Bits) {
	  var form = layui.form;
      var resArry = [];
      var xresArry = [];
      var permission;
      var inputs = document.getElementsByName("type");
      i = 0;
      //除2取余
      for (; num > 0;) {
           resArry.push(num % 2);
           num = parseInt(num / 2);
           i++;
       }
      //倒序排列
      for (j = i - 1; j >= 0; j--) {
           xresArry.push(resArry[j]);
       }
      //报错
      if (Bits < xresArry.length) {
          console.log("控制位小于转换位数");
      }
      //补0操作
      if (Bits) {
         for (r = xresArry.length; r < Bits; r++) {
             xresArry.unshift("0");
          }
       }
      permission =  xresArry.join().replace(/,/g, "");
      
      for(var i=0; i<permission.length;i++){
    	  if(permission[i] == 1){
    		  inputs[5-i].checked=true;
    	  }else{
    		  inputs[5-i].checked=false;
    	  }
      }
     
      form.render();
      return permission;
 }

</script>
</html>